function vl_test_hikmeans
% VL_TEST_HIKMEANS Test VL_HIKMEANS function

K        = 2;
nleaves  = 2;
data     = uint8(rand(2,100)*255);
[tree,A] = vl_hikmeans(data,K,nleaves,'verbose','verbose');

%keyboard;

K        = 3 ;
nleaves  = 100 ;
data     = uint8(rand(2,1000) * 255) ;
datat    = uint8(rand(2,10000)* 255) ;

[tree,A] = vl_hikmeans(data,K,nleaves,'verbose', 'verbose') ;
AT       = vl_hikmeanspush(tree,datat,'verbose','verbose') ;

%keyboard

figure(1) ; clf ; 
plottree(tree) ;
axis off ; axis equal ; xlim([0 255]) ; ylim([0 255]) ;
vl_demo_print('hikmeans-tree') ;
 
figure(2) ; clf ; hold on ;
hold on ;
cl = get(gca,'ColorOrder') ;
ncl = size(cl,1) ;
for k=1:K*K
  sel=find(A(end,:)==k) ;  
  plot(data(1,sel),data(2,sel),  '.','Color',cl(mod(k,ncl)+1,:)) ;
  sel=find(AT(end,:)==k) ;
  plot(datat(1,sel),datat(2,sel),'+','Color',cl(mod(k,ncl)+1,:)) ;  
end
h=plottree(tree) ;
set(h,'LineWidth',4) ;

axis off ; axis equal ; xlim([0 255]) ; ylim([0 255]) ;
vl_demo_print('hikmeans-clusters') ;

% --------------------------------------------------------------------
function h=plottree(tree)
% --------------------------------------------------------------------
% PLOTTRE  Plot hierarchical K-means tree
%   PLOTTREE(TREE) plots a tree generated by HIKMEASN(). 
%
%   See also VL_HIKMEANS().

x1=[] ;
x2=[] ;
for c=1:size(tree.centers,2)
  [x1p x2p]=xplot(tree.centers(:,c), tree.sub(c)) ;
  x1 = [x1 x1p] ;
  x2 = [x2 x2p] ;
end
h=line(x1(:),x2(:)) ;

% --------------------------------------------------------------------
function [x1,x2]=xplot(X,tree)
% --------------------------------------------------------------------
x1=[] ;
x2=[] ;
if(~isstruct(tree)), return ; end ;

C  = size(tree.centers,2) ;
x1 = [double(X(1))*ones(1,C); double(tree.centers(1,:)); nan*ones(1,C)] ;
x2 = [double(X(2))*ones(1,C); double(tree.centers(2,:)); nan*ones(1,C)] ;


if(any(x1>300)), keyboard ;end

if ~isempty(tree.sub)
  for c=1:C
    [x1p x2p]=xplot(tree.centers(:,c), tree.sub(c)) ;
    x1 = [x1 x1p] ;
    x2 = [x2 x2p] ;
  end
end
